<template>
  <view class="time-container" :style="{ width: width, color: color  }">
    <text>{{ timeText }}</text>
  </view>
</template>

<script setup lang="ts">
  import {
    ref,
    defineProps,
    defineEmits,
    defineExpose,
    onUnmounted
  } from "vue";

  import { getFormatTime } from "@/utils/util";

  const props = defineProps({
    color: {
      type: String,
      default: '#A87F71'
    },
    width: {
      type: String,
      default: '6rem'
    },
    seconds: {
      type: Number,
      default: 0
    },
    autoplay: {
      type: Boolean,
      default: true
    }
  });

  let timer: any = null;

  let timeText = ref('');

  const emit = defineEmits(['update:seconds']);

  const start = () => {
    update();
    timer = setInterval(() => update(), 1000);
    function update() {
      setText(props.seconds);
      let seconds = Number(props.seconds);
      emit('update:seconds', ++seconds);
    }
  }

  const setText = (seconds: number) => (timeText.value = getFormatTime(seconds, 'mm-ss', ':'));

  const destroy = () => {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  }

  (() => {
    setText(props.seconds);
    props.autoplay && start();
  })();

  onUnmounted(() => {
    destroy();
  });

  defineExpose({
    start,
    destroy
  });
</script>

<style scoped lang="scss">
  .time-container {
  }
</style>